package com.swak.rabbit.original;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

import com.rabbitmq.client.AMQP.BasicProperties;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.DefaultConsumer;
import com.rabbitmq.client.Envelope;
import com.rabbitmq.client.GetResponse;
import com.swak.utils.StringUtils;

/**
 * 主要测试在消费者注册回调和主动获取数据的模式下； 客户端和服务器的数据时推模型还是拉模型；
 * 
 * @author 618lf
 */
public class OriginalTestConsumer {

	static String exchangeName = "Test.test2_return_exchange";
	static String routingKey = "return.#";
	static String queueName = "Test.test2_return_queue";

	public static void consume() throws IOException, TimeoutException {
		ConnectionFactory connectionFactory = new ConnectionFactory();
		connectionFactory.setHost("192.168.137.100");
		connectionFactory.setUsername("admin");
		connectionFactory.setPassword("admin");
		connectionFactory.setPort(5672);
		connectionFactory.setVirtualHost("/");
		Connection connection = connectionFactory.newConnection();
		Channel channel = connection.createChannel();
		channel.basicQos(1);
		channel.basicConsume(queueName, true, new DefaultConsumer(channel) {
			@Override
			public void handleDelivery(String consumerTag, Envelope envelope, BasicProperties properties, byte[] body)
					throws IOException {
				System.out.println("收到数据: " + StringUtils.newStringUtf8(body));
				try {
					Thread.sleep(5000);
				} catch (Exception e) {
				}
			}
		});
	}

	public static void consume2() throws IOException, TimeoutException, InterruptedException {
		ConnectionFactory connectionFactory = new ConnectionFactory();
		connectionFactory.setHost("192.168.137.100");
		connectionFactory.setUsername("admin");
		connectionFactory.setPassword("admin");
		connectionFactory.setPort(5672);
		connectionFactory.setVirtualHost("/");
		Connection connection = connectionFactory.newConnection();
		Channel channel = connection.createChannel();
		channel.basicQos(1);
		for (;;) {
			GetResponse response = channel.basicGet(queueName, false);
			if (response != null && response.getMessageCount() != 0) {
				System.out.println("获取数据：" + StringUtils.newStringUtf8(response.getBody()));
			} else {
				System.out.println("没有获取数据！");
			}
			Thread.sleep(2000);
		}
	}

	public static void main(String[] args) throws IOException, TimeoutException, InterruptedException {
		// consume();
		consume2();
	}
}